package com.company.cloud.mall.modules.app.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.function.Function;

import com.alibaba.fastjson.JSON;
import com.company.cloud.user.modules.api.response.UserFull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.YNEnum;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.mall.modules.api.response.OrderModel;
import com.company.cloud.mall.modules.app.controller.req.OrderByProductSingleSaveParam;
import com.company.cloud.mall.modules.app.controller.req.OrderExchangeParam;
import com.company.cloud.mall.modules.app.controller.req.OrderQuery4PageParam;
import com.company.cloud.mall.modules.app.controller.req.OrderSaveParam;
import com.company.cloud.mall.modules.app.controller.req.OrderTicketCodeCheckParam;
import com.company.cloud.mall.modules.app.service.ShopOrderService;
import com.company.cloud.mall.modules.base.entity.OrderInfo;
import com.company.cloud.mall.modules.base.service.OrderInfoService;
import com.company.cloud.mall.modules.cache.models.OrderNumStatisticsModel;
import com.company.cloud.mall.modules.cache.service.ShopOrderCacheService;
import com.company.cloud.mall.modules.utils.ShopOrderConvertUtils;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.api.service.UserRemoteService;

import cn.hutool.core.lang.Dict;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;

/**
 * 订单信息
 */
@Log4j2
@Login
@RestController
@RequestMapping("/app/mall/order")
@Api(tags = "Shop_订单")
public class OrderInfoController {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private ShopOrderService shopOrderService;

    @Autowired
    private ShopOrderCacheService shopOrderCacheService;

    @Autowired
    private UserRemoteService userRemoteService;

    @PostMapping("/query")
    @ApiOperation(value = "用户订单列表查询", response = OrderModel.class)
    public BaseResult query(@RequestBody OrderQuery4PageParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        params.setUserId(userInfo.getId());
        params.setUserDelState(YNEnum.YES.getCode());
        params.setItem(true);
        params.setBusiness(true);
        params.setAfter(true);
        params.setUser(false);
        IPage<OrderModel> data = shopOrderService.queryUserOrders(params, userInfo);
        return BaseResult.ok(data);
    }

    @PostMapping("/queryOrderByReferral")
    @ApiOperation(value = "推荐人订单查询", response = OrderModel.class)
    public BaseResult queryOrderByReferral(@RequestBody OrderQuery4PageParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        params.setReferralUserId(userInfo.getId());
//		LoginSimpleUserInfo userInfo= AuthContextUtils.getUserNoValidate();
//		params.setReferralUserId(46);
        params.setUserDelState(YNEnum.YES.getCode());
        params.setItem(true);
        params.setBusiness(true);
        params.setAfter(false);
        params.setUser(true);
        IPage<OrderModel> data = shopOrderService.queryUserOrders(params, userInfo);
        return BaseResult.ok(data);
    }

    @GetMapping("/orderNumStatistics")
    @ApiOperation(value = "用户订单数统计", response = OrderNumStatisticsModel.class)
    public BaseResult orderNumStatistics() {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        OrderNumStatisticsModel data = shopOrderCacheService.getOrderNumStatisticsByDB(userInfo.getId());
        return BaseResult.ok(data);
    }

    @PostMapping("/saveByCustMultiple")
    @ApiOperation(value = "多商户订单新增")
    public BaseResult saveByCustMultiple(@RequestBody OrderSaveParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        String shareCode = AuthContextUtils.getShareCode();
        UserSimple shareUser = null;
        if (StringUtils.hasText(shareCode)) {
            BaseClientResult<UserSimple> userSimpleResp = userRemoteService.getUserByShareCode(shareCode);
            shareUser = BaseClientResult.getResultData(userSimpleResp);
        }

        List<OrderInfo> orderList;
        if (shareUser != null && CheckUtils.hasInt(shareUser.getId())) {
            orderList = shopOrderService.saveOrderByCustMultiple(userInfo.getId(), shareUser.getId(), shareCode, params,
                    userInfo);
        } else {
            orderList = shopOrderService.saveOrderByCustMultiple(userInfo.getId(), userInfo.getReferralUserId(),
                    userInfo.getReferralCode(), params, userInfo);
        }
        Dict data = Dict.create();
        if (!CollectionUtils.isEmpty(orderList)) {
            List<OrderModel> orderDictList = new ArrayList<OrderModel>();
            orderList.forEach(order -> {
                OrderModel orderModel = ShopOrderConvertUtils.getOrderModel(order, null, null, null, null, null, new HashMap<>());
                orderDictList.add(orderModel);
            });
            data.put("list", orderDictList);
        }
//		shopOrderCacheService.removeOrderNumStatisticsByCache(userInfo.getId());
        return BaseResult.ok(data);
    }

    @PostMapping("/saveByProductSingle")
    @ApiOperation(value = "单商品订单新增")
    public BaseResult saveByProductSingle(@RequestBody OrderByProductSingleSaveParam params) {
        System.out.println(JSON.toJSONString(params));
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        String shareCode = AuthContextUtils.getShareCode();
        UserSimple userSimple = null;
        if (StringUtils.hasText(shareCode)) {
            // todo
            BaseClientResult<UserSimple> userSimpleResp = userRemoteService.getUserByShareCode(shareCode);
            userSimple = BaseClientResult.getResultData(userSimpleResp);
        }
        OrderInfo entity;
        if (userSimple != null && CheckUtils.hasInt(userSimple.getId())) {
            entity = shopOrderService.saveOrderByProductSingle(userInfo.getId(), userSimple.getId(), null, params, userInfo);
        } else {
            entity = shopOrderService.saveOrderByProductSingle(userInfo.getId(), userInfo.getReferralUserId(), userInfo.getReferralCode(), params, userInfo);
        }
        OrderModel data = ShopOrderConvertUtils.getOrderModel(entity, null, null, null, null, null, new HashMap<>());
//		shopOrderCacheService.removeOrderNumStatisticsByCache(userInfo.getId());
        return BaseResult.ok(data);
    }

    @GetMapping("/get")
    @ApiOperation(value = "订单明细", response = OrderModel.class)
    public BaseResult get(@RequestParam("sn") String sn) {
        OrderModel data = shopOrderService.getOrder(sn, true, false, true, true, true);
        return BaseResult.ok(data);
    }

    @GetMapping("/close")
    @ApiOperation(value = "订单关闭")
    public BaseResult close(@RequestParam("sn") String sn) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        shopOrderService.close(sn, userInfo);
//		shopOrderCacheService.removeOrderNumStatisticsByCache(userInfo.getId());
        return BaseResult.ok();
    }

    @GetMapping("/complete")
    @ApiOperation(value = "确认收货完成订单")
    public BaseResult complete(@RequestParam("sn") String sn) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        shopOrderService.complete(sn, userInfo);
//		shopOrderCacheService.removeOrderNumStatisticsByCache(userInfo.getId());
        return BaseResult.ok();
    }

    @GetMapping("/del")
    @ApiOperation(value = "用户删除订单")
    public BaseResult del(@RequestParam("sn") String sn) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        shopOrderService.removeByUser(sn, userInfo);
//		shopOrderCacheService.removeOrderNumStatisticsByCache(userInfo.getId());
        return BaseResult.ok();
    }

    @GetMapping("/exchangePoint")
    @ApiOperation(value = "订单兑换积分")
    public BaseResult exchangePoint(@RequestParam("sn") String sn) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        shopOrderService.exchangePoint(sn, userInfo);
        return BaseResult.ok();
    }

    @PostMapping("/queryByBusiness")
    @ApiOperation(value = "商户订单列表查询", response = BaseResult.class)
    public BaseResult queryByBusiness(@RequestBody OrderQuery4PageParam params) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
//		params.setBusiNo(userInfo.getBusiNo());
        params.setItem(true);
        params.setBusiness(false);
        IPage<OrderModel> page = shopOrderService.queryUserOrders(params, userInfo);
        if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
            return BaseResult.ok();
        }
        IPage<OrderModel> data = page.convert(new Function<OrderModel, OrderModel>() {
            @Override
            public OrderModel apply(OrderModel entity) {
                entity.setExchangeCode(null);
                return entity;
            }
        });
        return BaseResult.ok(data);
    }

    @PostMapping("/exchangeByBusiness")
    @ApiOperation(value = "商户订单兑换", response = BaseResult.class)
    public BaseResult exchangeByBusiness(@RequestBody OrderExchangeParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        shopOrderService.send(params, userInfo);
        return BaseResult.ok();
    }

    @PostMapping("/checkTicketCode")
    @ApiOperation(value = "核销码核销", response = BaseResult.class)
    public BaseResult checkTicketCode(@RequestBody OrderTicketCodeCheckParam params) {
        ValidatorUtils.validate(params);
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        shopOrderService.checkTicket(params, userInfo);
        return BaseResult.ok();
    }

    @PostMapping("/ticket/single/save")
    @ApiOperation(value = "单商品订单新增")
    public BaseResult saveTicketByProductSingle(@RequestBody OrderByProductSingleSaveParam params) {
        ValidatorUtils.validate(params);
        BaseClientResult<UserFull> userResult = userRemoteService.getFullUserById(params.getUserId());
        UserFull userSimple = userResult.getData();
        LoginSimpleUserInfo userInfo = new LoginSimpleUserInfo();
        userInfo.setId(userSimple.getId());
        userInfo.setCompanyNo(userSimple.getCompanyNo());
        userInfo.setUserTypeOne(userSimple.getUserTypeOne());
        userInfo.setUserTypeTwo(userSimple.getUserTypeTwo());
        userInfo.setUserName(userSimple.getUserName());
        userInfo.setIp(userSimple.getRegIp());
        userInfo.setToken(userInfo.getToken());
        OrderInfo entity = shopOrderService.saveOrderByProductSingle(userInfo.getId(), userInfo.getReferralUserId(), userInfo.getReferralCode(), params, userInfo);
        OrderModel data = ShopOrderConvertUtils.getOrderModel(entity, null, null, null, null, null, new HashMap<>());
        return BaseResult.ok(data);
    }

}
